package com.ft.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ft.domain.Buyorder;
import com.ft.dao.BuyorderDao;
import com.ft.service.IBuyorderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author com/ft
 * @since 2022-08-24
 */
@Service
public class BuyorderServiceImpl extends ServiceImpl<BuyorderDao, Buyorder> implements IBuyorderService {
    @Autowired
    private BuyorderDao buyorderDao;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 创建帮我买订单
     * @param order 帮我买订单对象
     * @return 受影响的行数
     */
    @Override
    public int createBuyOrder(Buyorder order){
        /**先存redis,在存数据库，最后存数据库成功后进行校验，保证数据库和redis里都有数据并且一致
         *
         */
        //1.封装订单编号，存入buyorderZset集合中
        //获取添加Zset前的个数
        Long oldBuyOrderId = redisTemplate.opsForZSet().zCard("buyorderId");
        String id = String.valueOf(order.getId());
        redisTemplate.opsForZSet().add("buyorderId",id,0);
        //2.封装订单信息，存入Hash里
        String orderStr = JSON.toJSONString(order);
        redisTemplate.opsForHash().put("buyOrderHash",id,orderStr);
        //再存数据库
        int buyOrder = buyorderDao.createBuyOrder(order);
        /**
         * 数据校验，保证数据一致性
         */
        if (buyOrder == 1 ){
            while (true){
                //获取添加后的Zset个数
                Long newBuyOrderId = redisTemplate.opsForZSet().zCard("buyorderId");
                //获取存入redis的数据
                String hashOrderStr = (String) redisTemplate.opsForHash().get("buyOrderHash",id);
                //结束条件
                if(newBuyOrderId > oldBuyOrderId &! "".equals (hashOrderStr) & hashOrderStr.length () > 0){
                    break;
                }
                //对存入订单id进行校验
                if(newBuyOrderId <= oldBuyOrderId){
                    redisTemplate.opsForZSet().add("buyorderId",id,0);
                    continue;
                }
                //对存入订单信息进行校验
                if ("".equals (hashOrderStr) | hashOrderStr.length () == 0){
                    redisTemplate.opsForHash().put("buyOrderHash",id,orderStr);
                    continue;
                }

            }
            return 1;
        }else {
            return 0;
        }
    }

    @Override
    public Buyorder selectBuyOrder(Long id) {
        Buyorder buyorder = buyorderDao.selectBuyOrder(id);
        return buyorder;
    }

    @Override
    public Buyorder selectBuyOrderToPay(Long id) {
        Buyorder buyorder = buyorderDao.selectBuyOrderToPay(id);
        return buyorder;
    }

}
